<?php

namespace App\Http\Controllers;

use App\Models\Topic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopicRequest;
use App\Models\Category;
use Auth;
use App\Base\Handlers\ImageUploadHandler;
use App\Models\User;
use App\Models\Link;
use Illuminate\Support\Facades\Storage;

class TopicsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

    public function index(Request $request, Topic $topic, User $user, Link $link)
    {
        $topics = $topic->withOrder($request->order)->paginate(20);
        $active_users = $user->getActiveUsers();
        $links = $link->getAllCached();
        return view('topics.index', compact('topics', 'active_users', 'links'));
    }

    public function create(Topic $topic)
    {
        $categories = Category::all();
        return view('topics.create_and_edit', compact('topic', 'categories'));
    }

    public function store(TopicRequest $request, Topic $topic)
    {
        $topic->fill($request->all());
        $topic->user_id = Auth::id();
        $topic->save();

        return redirect()->to($topic->link())->with('success', '成功创建主题！');
    }

    /**
     * 上传图片
     *
     * @param Request $request
     * @param ImageUploadHandler $uploader
     * @return array|mixed|null
     */
    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
        $uploadImgType = env('UPLOAD_IMAGE_TYPE');
        $uploadResult = null;
        switch ($uploadImgType) {
            case 'local':
                // 本地上传文件
                $uploadResult = $this->uploadImageToLocal($request, $uploader);
                break;
            case 'net':
                // 上传文件到七牛
                $uploadResult = $this->uploadImageToNet($request);
                break;
        }
        return $uploadResult;
    }

    /**
     * 上传图片到本地
     *
     * @param Request $request
     * @return mixed
     */
    private function uploadImageToNet(Request $request)
    {
        $file = $request->upload_file;
        $filename = 'images/avatar' . md5(time() . user()->id) . '.' . $file->getClientOriginalExtension();
        $result = Storage::disk('qiniu')->writeStream($filename, fopen($file->getRealPath(), 'r'));
        // 图片保存成功的话
        if ($result) {
            $data['file_path'] = 'http://' . config('filesystems.disks.qiniu.domain') . '/' . $filename;;
            $data['msg'] = "上传成功!";
            $data['success'] = true;
        }
        return $data;
    }

    /**
     * 上传图片到本地
     *
     * @param Request $request
     * @param ImageUploadHandler $uploader
     * @return array
     */
    private function uploadImageToLocal(Request $request, ImageUploadHandler $uploader)
    {
        // 初始化返回数据，默认是失败的
        $data = [
            'success' => false,
            'msg' => '上传失败!',
            'file_path' => ''
        ];
        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploader->save($request->upload_file, 'topics', \Auth::id(), 1024);
            // 图片保存成功的话
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['msg'] = "上传成功!";
                $data['success'] = true;
            }
        }
        return $data;
    }

    /**
     * 展示话题
     *
     * @param Request $request
     * @param Topic $topic
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function show(Request $request, Topic $topic)
    {
        // URL 矫正
        if (!empty($topic->slug) && $topic->slug != $request->slug) {
            return redirect($topic->link(), 301);
        }

        return view('topics.show', compact('topic'));
    }

}
